// useSpeakQueue.ts
interface SpeakQueueItem {
  text: string
  repeat?: number // 每条播放多少次，默认 1
  onFinish?: () => void
}

interface Options {
  autoStart?: boolean
}

export function useSpeakQueue() {
  let queue: SpeakQueueItem[] = [];
  let isSpeaking = false;
  let destroyed = false;
  let defaultRepeat = 1;
  let ttsModule: any;

  // #ifdef APP-PLUS
  // eslint-disable-next-line prefer-const
  ttsModule = uni.requireNativePlugin('XWC-TTS');
  // #endif

  /** 初始化播报模块 */
  function initSpeakQueue(options: { defaultRepeat?: number } = {}) {
    destroyed = false;
    defaultRepeat = options.defaultRepeat || 1;
    // #ifdef APP-PLUS
    // 初始化语音播放请求
    ttsModule.init(res => {
      console.log('语音播放初始化结果：', res);
    });
  // #endif
  }

  /** 添加到播放队列 */
  function addToSpeakQueue(item: SpeakQueueItem | string, options: Options = {}) {
    if (typeof item === 'string') {
      item = { text: item };
    }

    item.repeat = item.repeat || defaultRepeat;
    queue.push(item);

    if (!isSpeaking && options.autoStart !== false) {
      playNext(options);
    }
  }

  /** 播放下一条队列 */
  function playNext(options: Options = {}) {
    if (destroyed)
      return;
    const item = queue.shift();
    if (!item) {
      isSpeaking = false;
      return;
    }

    isSpeaking = true;
    let count = item.repeat || 1;

    const play = () => {
      if (destroyed)
        return;
      // #ifdef APP-PLUS
      ttsModule.speak(item.text, (res: any) => {
        console.log('语音播放完成:', res);
        count--;
        if (count > 0) {
          setTimeout(play, 300); // 重复播放间隔
        }
        else {
          item.onFinish?.();
          playNext(options);
        }
      });
      // #endif
    };

    play();
  }

  /** 清空播放队列并中断当前播放 */
  function destroySpeakQueue() {
    destroyed = true;
    isSpeaking = false;
    queue = [];
    // #ifdef APP-PLUS
    ttsModule.free();
  // #endif
  }

  return {
    initSpeakQueue,
    addToSpeakQueue,
    destroySpeakQueue
  };
}
